#!/usr/bin/python3

import glob
import imp
import os
import string
import subprocess
import sys
import unittest
import inspect

import parent
import testlib
import testvm

sys.dont_write_bytecode = True

def check_valid(filename):
    name = os.path.basename(filename)
    allowed = string.ascii_letters + string.digits + '-_'
    if not all(c in allowed for c in name):
        return None
    return name.replace("-", "_")


def run(opts):
    # Now actually load the tests, any modules that start with "check-*"
    loader = unittest.TestLoader()
    suite = unittest.TestSuite()
    persistent_machine_suites = []
    for filename in glob.glob(os.path.join(os.path.dirname(__file__), "check-*")):
        name = check_valid(filename)
        if not name or not os.path.isfile(filename):
            continue
        with open(filename, 'rb') as fp:
            module = imp.load_module(name, fp, filename, ("", "rb", imp.PY_SOURCE))
            for name, obj in inspect.getmembers(module):
                if inspect.isclass(obj):
                    # subclasses of MachineCase
                    if obj != testlib.MachineCase and issubclass(obj, testlib.MachineCase):
                        suite.addTests(loader.loadTestsFromTestCase(obj))
                    # subclasses of PersistentMachineCase
                    elif (obj != testlib.PersistentMachineCase and
                          issubclass(obj, testlib.PersistentMachineCase)):
                        persistent_machine_suites.append(loader.loadTestsFromTestCase(obj))
                    # tests which aren't a MachineCase or a PersistentMachineCase
                    elif (issubclass(obj, unittest.TestCase)
                          and not (issubclass(obj, testlib.MachineCase) and issubclass(obj, testlib.PersistentMachineCase))):
                        suite.addTests(loader.loadTestsFromTestCase(obj))

    # And now load new testlib, and run all the tests we got
    return testlib.test_main(options=opts, suite=suite, persistent_machine_suites=persistent_machine_suites)


def main():
    parser = testlib.arg_parser()
    parser.add_argument('--publish', action='store', help="Unused")
    parser.add_argument('image', action='store', nargs='?',
                        help='The operating system image to verify against')
    opts = parser.parse_args()

    image = opts.image or testvm.DEFAULT_IMAGE

    revision = os.environ.get("TEST_REVISION")
    test_browser = os.environ.get("TEST_BROWSER", "chromium")
    if not revision:
        revision = subprocess.check_output(["git", "rev-parse", "HEAD"],
                                           universal_newlines=True).strip()

    # Tell any subprocesses what we are testing
    os.environ["TEST_REVISION"] = revision
    os.environ["TEST_BROWSER"] = test_browser
    testvm.DEFAULT_IMAGE = image
    os.environ["TEST_OS"] = image

    return run(opts)


if __name__ == '__main__':
    sys.exit(main())
